package com.common.base.utils

import android.content.Context
import android.os.Environment
import java.io.File
import java.math.BigDecimal

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2023/11/26
 *
 * 描述：
 *
 * 修订历史：
 *
 */
object CacheManager {
    /**
     * 获取缓存大小
     */
    fun getTotalCacheSize(context: Context): String {
        var cacheSize: Long = 0
        try {
            cacheSize = getFolderSize(context.cacheDir)
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                cacheSize += getFolderSize(context.externalCacheDir)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return getFormatSize(cacheSize.toDouble())
    }

    /**
     * 清除缓存
     */
    fun clearAllCache(context: Context) {
        deleteDir(context.cacheDir)
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            deleteDir(context.externalCacheDir)
        }
    }

    private fun deleteDir(dir: File?): Boolean {
        if (dir != null && dir.isDirectory) {
            val children = dir.list()
            for (child in children) {
                val success = deleteDir(File(dir, child))
                if (!success) {
                    return false
                }
            }
        }
        return dir != null && dir.delete()
    }

    /**
     * 清除WebView缓存
     */
    fun clearWebViewCache(context: Context) {

        //清理Webview缓存数据库
        try {
            context.deleteDatabase("webview.db")
            context.deleteDatabase("webviewCache.db")
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //WebView 缓存文件
        val appCacheDir = File(context.filesDir.absolutePath + "/webcache")
        //        Log.e(TAG, "appCacheDir path=" + appCacheDir.getAbsolutePath());
        val webviewCacheDir = File(context.cacheDir.absolutePath + "/webviewCache")
        //        Log.e(TAG, "webviewCacheDir path=" + webviewCacheDir.getAbsolutePath());

        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteDir(webviewCacheDir)
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteDir(appCacheDir)
        }
        deleteDir(File(context.filesDir.parent?.plus("/app_webview") ?: ""))
    }

    // 获取文件大小
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    //getCacheDir()方法用于获取/data/data//cache目录
    //getFilesDir()方法用于获取/data/data//files目录
    @Throws(Exception::class)
    fun getFolderSize(file: File?): Long {
        var size: Long = 0
        try {
            val fileList = file!!.listFiles()
            for (value in fileList) {
                // 如果下面还有文件
                size = if (value.isDirectory) {
                    size + getFolderSize(value)
                } else {
                    size + value.length()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return size
    }

    /**
     * 格式化单位
     */
    fun getFormatSize(size: Double): String {
        val kiloByte = size / 1024
        if (kiloByte < 1) {
            //            return size + "Byte";
            return "0.0 KB"
        }
        val megaByte = kiloByte / 1024
        if (megaByte < 1) {
            val result1 = BigDecimal(kiloByte.toString())
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                .toPlainString() + "KB"
        }
        val gigaByte = megaByte / 1024
        if (gigaByte < 1) {
            val result2 = BigDecimal(megaByte.toString())
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                .toPlainString() + "MB"
        }
        val teraBytes = gigaByte / 1024
        if (teraBytes < 1) {
            val result3 = BigDecimal(gigaByte.toString())
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                .toPlainString() + "GB"
        }
        val result4 = BigDecimal(teraBytes)
        return (result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB")
    }

    fun deleteFilesInDirectoryExceptSpecificFile(directoryPath: String, exceptFileName: String) {
        // 创建File对象
        val directory = File(directoryPath)
        // 检查File是否是目录
        if (directory.isDirectory) {
            // 列出所有文件
            val files = directory.listFiles()
            if (files != null) {
                for (file in files) {
                    // 检查文件名是否与要保留的文件名不同
                    if (file.isFile && file.name != exceptFileName) {
                        // 删除文件
                        file.delete()
                    }
                }
            }
        }
    }
}